import java.io.*
import java.util.concurrent.TimeUnit
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.exec.ExecuteException
import org.apache.commons.exec.PumpStreamHandler
import org.slf4j.LoggerFactory

val ADB = if (args.size > 0) "adb -s ${args[0]}" else "adb"
val log = LoggerFactory.getLogger("Helper")

fun String.check_call(): Boolean {
    var ret: Boolean
    try {
        val cmd = CommandLine.parse(this)
        log.info(cmd.toString())
        DefaultExecutor().execute(cmd)
        ret = true
    } catch (e: java.lang.IllegalArgumentException) {
        log.error("$e: can not parse command: [$this]")
        throw e
    } catch (e: ExecuteException) {
        log.error("$e: can not exec command")
        //throw e
        TimeUnit.SECONDS.sleep(10)
        ret = false
    } catch (e: IOException) {
        log.error("$e: can not exec command")
        throw e
    }
    return ret
}

for (loop in 1 .. 1000) {
    "$ADB logcat".check_call()
    log.info("Logcat Round $loop")
    println("Logcat Round $loop")
    TimeUnit.SECONDS.sleep(10)
}
